<template>
  <div ref="editorContainerRef" style="height: 100%; width: 100%;"></div>
</template>

<script setup>
import * as monaco from 'monaco-editor';
import {ref, onMounted, onBeforeUnmount, watch, nextTick, toRaw } from 'vue';

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'shell'
  },
  fontsize: {
    type: Number,
    default: 18
  }
});

const emit = defineEmits(['update:value', 'change']);

const editorContainerRef = ref(null);
const editorInstance = ref(null);
let ignoreNextChange = false;

const initEditor = async () => {
  await nextTick();

  if (editorContainerRef.value && !editorInstance.value) {
    editorInstance.value = monaco.editor.create(editorContainerRef.value, {
      value: props.value || '',
      language: props.language || 'rust',
      minimap: {
        enabled: true,
      },
      colorDecorators: true,
      readOnly: false,
      theme: "vs-dark",
      automaticLayout: true,
      fontSize: props.fontsize || 18
    });

    // 监听编辑器内容变化
    editorInstance.value.onDidChangeModelContent((e) => {
      if (ignoreNextChange) {
        ignoreNextChange = false;
        return;
      }
      const newValue = toRaw(editorInstance.value).getValue();
      if (newValue !== props.value) {
        emit('update:value', newValue);
        emit('change', newValue);
      }
    });
  }
};

// 监听 props.value 的变化
watch(() => props.value, (newValue) => {
      if (!editorInstance.value) return;
      const currentValue = toRaw(editorInstance.value).getValue();
      if (newValue !== currentValue) {
        ignoreNextChange = true;
        toRaw(editorInstance.value).setValue(newValue || '');
      }
    }
);

onMounted(() => {
  initEditor();
});

onBeforeUnmount(() => {
  if (editorInstance.value) {
    editorInstance.value.dispose();
    editorInstance.value = null;
  }
});
</script>